/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from 'react'
import {actions} from "../../../../reducers/main"
import { connect } from 'react-redux'
import {withRouter} from "react-router-dom"
import {message, Spin, Table, Switch, Button, Icon, Pagination, Modal, Tag} from 'antd'
import MyForm from '../../../components/Form'
import axios from '../../../../apis/api'
import {host} from '../../../../config/config'
import AccountForm from './AccountForm'
import qs from 'qs'
import GroupForm from "../accountGroup";


const mapStateToProps = (state, ownProps) => {
    return {
        vwAgentCashStat: state.main.vwAgentCashStat,
        vwAgentCashDayStat: state.main.vwAgentCashDayStat,
        isChannel: state.main.isChannel,
        payTypeList: state.main.payTypeList, // 支付类型
        groups: state.main.groups, // 分组
        agentList: state.main.agentList, // 码商带来
        banks: state.main.banks, // 银行
        address: state.main.address, //模拟地址
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        fetchInitData: (next) => dispatch(actions.fetchInitData(next))
    }
}

const formItems = [{
    label: '账户',
    key: 'account',
    type: 'input'
}, {
    label: '支付类型',
    key: 'payType',
    type: 'select',
    options: [{
        label: '所有',
        value: ''
    }]
}, {
    label: '分组',
    key: 'groupName',
    type: 'select',
    options: [{
        label: '所有',
        value: ''
    }]
}, {
    label: '账户状态',
    key: 'status',
    type: 'select',
    options: [{
        label: '所有',
        value: ''
    }, {
        label: '正常',
        value: 0
    }, {
        label: '停用',
        value: 1
    }]
},{
    label: '码商代理',
    key: 'channelUserId',
    type: 'select',
    options: [{
        label: '所有',
        value: ''
    }]
}]

class ChannelOrder extends Component {
    state = {
        initForm: {
            account: '',
            payType: '',
            groupName: '',
            status: '',
            channelUserId: ''
        },
        formItmes: formItems,
        searchParam: {},
        loading: false,
        depMap: {},
        pageSize: 10,
        curPage: 1,
        tableData: {
            total: 0,
            rows: []
        },
        channels: [], // 码商代理
        proxys: [], // 商户代理
        payTypes: [], // 支付类型
        payTypesMap:{},
        visibleDlg: false,
        initOpenForm: {},
        formType: 'add',
        formTitle: '添加通道账户',
        orderStatusMap: {
            '1': {
                label: '停用',
                class: 'red'
            },
            '0': {
                label: '正常',
                class: 'green'
            }
        },
        curEdit: {},
        confirmLoading: false
    }

    handleSearch = (value) => {
        this.setState({
            curPage: 1,
            searchParam: value
        }, this.searchTable)
    }

    componentDidMount() {
        this.init()
    }
    init = async () => {
        try {
            this.setState({
                loading: true
            })
            this.searchTable()
            this.setState({
                loading: false
            })
        } catch (e) {
            this.setState({
                loading: false
            })
            message.error(e.message)
        }
    }

    searchTable = async () => {
        const {pageSize, curPage, searchParam} = this.state
        const query = {
            orderByColumn: 'createTime',
            isAsc: 'desc',
            pageSize,
            pageNum: curPage,
            payType: searchParam.payType,
            account: searchParam.account,
            groupName: searchParam.groupName,
            status: searchParam.status,
            channelUserId: searchParam.channelUserId
        }
        try {
            this.setState({
                loading: true
            })
            const result = await axios.post('/channel/channelAccount/list', qs.stringify(query))
            if (result.code === 0) {
                this.setState({
                    tableData: result,
                    loading: false
                })
            } else {
                this.setState({
                    loading: false
                })
                message.error(result.msg)
            }
        } catch (e) {
            this.setState({
                loading: false
            })
            message.error(e.message)
        }
    }
    //翻页
    handlePageChange = (page, pageSize) => {
        this.setState({
            curPage: page
        },this.searchTable)
    }

    jump2Test = (data) => {
        const newWindow = window.open(`${host}/pay/test?account=${data.accountId}&payType=${data.payType}`)
        if (!newWindow) {
            message.error('弹出窗口被拦截')
        }
    }

    delRow = (data) => {
        Modal.confirm({
            title: '系统提示',
            content: '确定删除该条通道账户信息吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const result = await axios.post('/channel/channelAccount/remove', qs.stringify({
                        ids: data.accountId
                    }))
                    if (result.code === 0) {
                        message.success(result.msg)
                    } else {
                        message.error(result.msg)
                    }
                    this.handlePageChange(1)
                } catch (e) {
                    message.error(e.message || e.msg)
                }
            },
            onCancel() {
            },
        })
    }

    go2ChildAccount = (data) => {
        this.props.history.push(`/main/channelAccount/subAccount/${data.accountId}`)
    }
    addAccount = () => {
        this.setState({
            visibleDlg: true,
            formType: 'add',
            initOpenForm: {},
            formTitle: '添加通道账户'
        })
    }
    //补单
    edit = (data) => {
        this.setState({
            visibleDlg: true,
            formType: 'edit',
            initOpenForm: JSON.parse(JSON.stringify(data)),
            formTitle: '修改通道账户',
            curEdit: data
        })
    }

    submitForm = async (data) => {
        this.setState({
            confirmLoading: true
        })
        if (this.state.formType === 'add') {
            try {
                // 校验名称重复不重复
                const checkResult = await axios.post('/channel/channelAccount/checkAccountUnique', qs.stringify({
                    account: data.account,
                    name: data.account,
                    payType: data.payType,
                }))
                if (checkResult === 1) {
                    message.error('该账号已存在')
                    this.setState({
                        confirmLoading: false
                    })
                    return
                }
                const result = await axios.post('/channel/channelAccount/add', qs.stringify(data))
                if (result.code === 0) {
                    message.success(result.msg)
                    this.cancelForm()
                    this.handlePageChange(1)
                } else {
                    message.error(result.msg)
                }
                this.setState({
                    confirmLoading: false
                })
            } catch (e) {
                this.setState({
                    confirmLoading: false
                })
                console.log(e)
                message.error(e.message || e.msg)
            }
        } else {
            try {
                const result = await axios.post('/channel/channelAccount/edit', qs.stringify({
                    ...data,
                    accountId: this.state.curEdit.accountId
                }))
                if (result.code === 0) {
                    message.success(result.msg)
                    this.cancelForm()
                    this.handlePageChange(1)
                } else {
                    message.error(result.msg)
                }
                this.setState({
                    confirmLoading: false
                })
            } catch (e) {
                console.log(e)
                message.error(e.message || e.msg)
                this.setState({
                    confirmLoading: false
                })
            }
        }
    }

    cancelForm = () => {
        this.setState({
            visibleDlg: false,
            confirmLoading: false
        })
    }

    onShowSizeChange = (current, pageSize) => {
        this.setState({
            pageSize: pageSize,
            curPage: current,
        }, this.searchTable)
    }

    render() {
        const {initForm, formItmes, loading, tableData, curPage, pageSize, payTypesMap, orderStatusMap} = this.state
        const {payTypeList, groups, agentList, banks, address} = this.props
        let formItem = JSON.parse(JSON.stringify(formItmes))
        formItem[1].options.push(...payTypeList.map(item => ({
            label: item.payLabel,
            value: item.payType
        })))
        formItem[2].options.push(...groups.map(item => ({
            label: item.groupName,
            value: item.groupName
        })))
        formItem[4].options.push(...agentList.map(item => ({
            label: item.userName,
            value: item.userId
        })))
        const columns = [{
            title: '码商代理',
            dataIndex: 'channelUserName',
            key: 'channelUserName'
        }, {
            title: '账号',
            dataIndex: 'account',
            key: 'account'
        }, {
            title: '别名',
            dataIndex: 'alias',
            key: 'alias'
        }, {
            title: '分组',
            dataIndex: 'groupName',
            key: 'groupName'
        }, {
            title: '支付类型',
            dataIndex: 'payLabel',
            key: 'payLabel'
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (value, data) => {
                return <Tag color={orderStatusMap[value].class} >
                    {orderStatusMap[value].label}
                </Tag>
            }
        }, {
            title: '剩余金额',
            dataIndex: 'amount',
            key: 'amount'
        },{
            title: '操作',
            dataIndex: 'actions',
            key: 'actions',
            fixed: 'right',
            render: (value, data) => {
                return <span>
                    <Button size={"small"} type="primary" onClick={() => this.edit(data)}>编辑</Button>
                    <Button size={"small"} type="primary" style={{marginLeft: 10}} onClick={() => this.jump2Test(data)}>测试</Button>
                    <Button size={"small"} type="danger" style={{marginLeft: 10}} onClick={() => this.delRow(data)}>删除</Button>
                    <Button size={"small"} type="primary" style={{marginLeft: 10}} onClick={() => this.go2ChildAccount(data)}>子账号</Button>
                </span>
            }
        }]
        return (
            <div>
                <MyForm initForm={initForm} items={formItem} handleSearch={this.handleSearch}/>
                <div style={{marginBottom: 10}}>
                    <Button type="primary" onClick={() => this.addAccount()}>添加</Button>
                </div>
                <Spin spinning={loading}>
                    <Table dataSource={tableData.rows} columns={columns} pagination={false} scroll={{x: true}}/>
                    <Pagination
                        style={{marginTop: 10, marginBottom: 20}}
                        total={tableData.total}
                        showTotal={total => `共 ${total} 项`}
                        pageSize={pageSize}
                        current={curPage}
                        pageSizeOptions={['10', '20', '50', '100', '500']}
                        showSizeChanger
                        onShowSizeChange={this.onShowSizeChange}
                        onChange={this.handlePageChange}
                    />
                </Spin>
                <AccountForm confirmLoading={this.state.confirmLoading} visible={this.state.visibleDlg} initForm={this.state.initOpenForm} title={this.state.formTitle} okCb={this.submitForm} cancelCb={this.cancelForm} />
            </div>
        )
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ChannelOrder))
